<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot + WebSocket + 广播式</title>
</head>
<body onload="disconnect()">
<noscript><h2 style="color:#ff0000" >貌似你的浏览器不支持</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" onclick="disconnect()" disabled="disabled">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name" />
        <button id="sendName" onclick="sendName()" >发送</button>
        <p id="response"></p>
    </div>
</div>

<script th:src="@{jquery-3.2.1.js}"></script>
<script th:src="@{sockjs.js}"></script>
<script th:src="@{stomp.js}"></script>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible': 'hidden';
        $("#response").html();
    }

    function connect() {
        var socket = new SockJS('/endpointWisely');     //1 连接sockJs的endpoint名称为"/endpointWisely"
        stompClient = Stomp.over(socket);       //2 使用stomp自协议的websocket客户端
        stompClient.connect({},function (frame) {   //3 连接websocket 服务端
            setConnected(true);
            console.log('Connected:' + frame);
            stompClient.subscribe('/topic/getResponse',function (response) {    //4 通过stompcoliet 订阅 /topic/getResponse
                // 目标 发送的消息,这个实在控制器@SendTo中定义的
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }

    function disconnect() {
        if (stompClient != null){
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("disconnected");
    }

    function sendName() {
        var name =$("#name").val();     //5 通过stomClient.send 向 /welcome 目标 (destionation 发送消息,这个实在控制器@MessageMapping 中定义的;
        stompClient.send("/welcome",{},JSON.stringify({'name':name}));
    }

    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }
</script>
</body>
</html>